<!-- 全局拉偏脚本 -->
<template>
    <el-drawer :visible.sync="drawer" :with-header="false" :direction="direction" @opened="initEditor">
        <div class="script-runner">

            <div class="s-r-top">
                <div class="s-r-top_item" @click="handleConfigClick('run')">
                    <el-tag>
                        <svg-icon style="margin-right: 5px;" icon-class="folder" width="14" height="14" />
                        {{ $t("tool.experimentDesign.run") }}
                    </el-tag>
                </div>
                <div class="s-r-top_item" @click="handleConfigClick('save')">
                    <el-tag>
                        <svg-icon style="margin-right: 5px;" icon-class="folder" width="14" height="14" />
                        {{ $t("tool.experimentDesign.save") }}
                    </el-tag>
                </div>
            </div>
            <splitpanes horizontal class="default-theme">
                <pane>
                    <div class="s-r-edit">
                        <div class="s-r-edit_title">
                            <svg-icon style="margin-right: 5px;" icon-class="folder" width="14" height="14" />
                            代码
                        </div>
                        <div ref="editorRef" class="s-r-edit_editor"></div>
                    </div>
                </pane>
                <pane min-size="8" max-size="70">
                    <div class="s-r-result">
                        <div class="s-r-result_title">
                            <svg-icon style="margin-right: 5px;" icon-class="folder" width="14" height="14" />
                            运行结果
                        </div>
                        <div class="s-r-result_content" v-loading="loading">
                            <div v-if="output">{{ output }}</div>
                            <div v-if="error" class="error">Error: {{ error }}</div>
                        </div>
                    </div>
                </pane>
            </splitpanes>


        </div>
    </el-drawer>

</template>

<script>
import * as monaco from 'monaco-editor';
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
export default {
    data() {
        return {
            drawer: false,
            direction: 'rtl',
            editor: null,
            code: `// 输入你的代码\nconst sum = (a, b) => a + b;\nconsole.log('1+2=', sum(1, 2));`,
            loading: false,
            output: '',
            error: '',
            editorOptions: {
                fontSize: 14,
                minimap: { enabled: false },
                lineNumbers: 'on'
            },
            customTheme: {
                "dark": {
                    base: 'vs-dark',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#191a23',
                    }
                },
                "darkblue": {
                    base: 'vs-dark',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#22272e',
                    }
                },
                "grey": {
                    base: 'vs-dark',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#242424',
                    }
                },
                "light": {
                    base: 'vs',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#ffffff',
                    }
                },
                "lightbrown": {
                    base: 'vs',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#f9f4e7',
                    }
                },
            }
        }
    },
    components: { Splitpanes, Pane },
    mounted() {
    },
    beforeDestroy() {
    },
    methods: {
        // 获取当前系统主题样式
        getSystemThemeStyle() {
            let themeConfig = localStorage.getItem("themeConfig")
            let backKeyWord = themeConfig.slice(0, themeConfig.search(/[A-Z]/));
            return {
                backKeyWord,
                themeConfig: this.customTheme[backKeyWord]
            }
        },
        initEditor() {

            // 获取主题
            let { backKeyWord, themeConfig } = this.getSystemThemeStyle()
            // 注册主题
            monaco.editor.defineTheme(backKeyWord, themeConfig);
            // 应用主题
            monaco.editor.setTheme(backKeyWord);
            if (this.editor) {
                return;
            }
            this.editor = monaco.editor.create(this.$refs.editorRef, {
                value: this.code || '',
                language: this.language,
                // theme: this.theme,
                wordWrap: 'off',
                renderLineHighlight: 'none',
                minimap: { enabled: false },
                fontSize: 14,
                lineHeight: 16,
                automaticLayout: true  // 关键：启用自动布局
            });

            // 内容同步
            this.editor.onDidChangeModelContent(() => {
                this.code = this.editor.getValue();
            });

            // 窗口尺寸监听（需配合CSS）
            // new ResizeObserver(() => this.editor.layout()).observe(this.$refs.editorRef);
        },
        runCode() {
            this.loading = true
            this.output = ''
            this.error = ''

            try {
                // 重写 console.log 捕获输出
                const logs = []
                const originalLog = console.log
                console.log = (...args) => logs.push(args.join(' '))
                // 执行代码
                const fn = new Function(this.code)
                fn()
                // 恢复 console
                console.log = originalLog
                // 显示输出
                this.output = logs.join('\n')
            } catch (e) {
                this.error = e.message
            }
            setTimeout(() => {
                this.loading = false
            }, 100)
        },
        handleKeyCommand(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                this.runCode()
            }
        },

        handleConfigClick(configName) {
            if (configName == "run") {
                this.runCode();
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.script-runner {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    .s-r-top {
        height: 35px;
        min-height: 35px;
        display: flex;
        justify-content: flex-end;
        border-bottom: 1px solid var(--ui-border-color-base);

        .s-r-top_item {
            display: flex;
            margin-right: 20px;
            align-items: center;
            font-size: var(--ui-font-size-base);
            cursor: pointer;

            .title-word {
                margin-left: 5px;
            }
        }
    }

    .s-r-edit {
        margin-top: 10px;
        height: 100%;

        .s-r-edit_title {
            background-color: var(--ui-component-background-alt);
            height: 30px;
            font-size: var(--ui-font-size-base);
            display: flex;
            align-items: center;
            padding-left: 10px;
        }

        .s-r-edit_editor {
            padding-top: 5px;
            border-radius: 10px;
            height: calc(100% - 30px);
        }
    }

    .s-r-result {
        height: 100%;
        .s-r-result_title {
            background-color: var(--ui-component-background-alt);
            height: 30px;
            font-size: var(--ui-font-size-base);
            display: flex;
            align-items: center;
            padding-left: 10px;
        }

        .s-r-result_content {
            padding-left: 10px;
            border-radius: 10px;
            overflow: auto;
            height: calc(100% - 30px);

            .error {
                color: #c00;
            }
        }
    }

}
</style>